package com.example.aslongastoday.ui.mine;

import static android.content.Context.MODE_PRIVATE;

import android.content.SharedPreferences;
import android.os.Bundle;

import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;

import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.example.aslongastoday.util.MD5Utils;
import com.example.aslongastoday.R;

import java.util.Random;

public class ForgotFragment extends Fragment implements View.OnTouchListener{

    private View view;
    private ImageView iv_back;

    private EditText user_name,psw,psw_again;

    private Button btn_find;
    private String userName,password,pswAgain;

    private TextView captchaText;
    private EditText captchaInput;
    private String captchaCode;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        view =inflater.inflate(R.layout.fragment_forgot, container, false);
        view.setOnTouchListener(this);

        iv_back = view.findViewById(R.id.iv_back);
        iv_back.setOnClickListener(new View.OnClickListener() {
            private FragmentManager fragmentManager;
            @Override
            public void onClick(View v) {
                //退出fragment
                fragmentManager = getActivity().getSupportFragmentManager();
                fragmentManager.popBackStack();
            }
        });

        captchaText = view.findViewById(R.id.captcha_text);
        captchaInput = view.findViewById(R.id.captcha_input);

        // 生成一个随机的验证码
        captchaCode = generateCaptchaCode();
        captchaText.setText("验证码: " + captchaCode);

        user_name = view.findViewById(R.id.forget_user_name);
        psw=view.findViewById(R.id.forget_psw);
        psw_again=view.findViewById(R.id.forget_psw_again);
        btn_find=view.findViewById(R.id.btn_find_psw);


        btn_find.setOnClickListener(new View.OnClickListener() {
            private FragmentManager fragmentManager;
            @Override
            public void onClick(View view) {
                getEditString();

                // md5Psw ; spPsw 为 根据从SharedPreferences中用户名读取密码
                if(TextUtils.isEmpty(userName)){
                    Toast.makeText(getContext(), "请输入用户名", Toast.LENGTH_SHORT).show();
                    return;
                }else if(TextUtils.isEmpty(password)){
                    Toast.makeText(getContext(), "请输入密码", Toast.LENGTH_SHORT).show();
                    return;
                }else if(TextUtils.isEmpty(pswAgain)){
                    Toast.makeText(getContext(),  "请再次输入密码", Toast.LENGTH_SHORT).show();
                    return;
                }else if(!password.equals(pswAgain)) {
                    Toast.makeText(getContext(), "输入两次的密码不一样", Toast.LENGTH_SHORT).show();
                    return;
                }else if(!captchaInput.getText().toString().equals(captchaCode)) {
                    Toast.makeText(getContext(), "验证码错误", Toast.LENGTH_SHORT).show();
                    return;
                }else if(isExistUserName(userName)){
                    /**
                     * 保存账号和密码到SharedPreferences中
                     */
                    saveRegisterInfo(userName, password);
                    Toast.makeText(getContext(), "修改成功", Toast.LENGTH_SHORT).show();
                    fragmentManager = getActivity().getSupportFragmentManager();
                    fragmentManager.popBackStack();
                    return;
                }else{
                    Toast.makeText(getContext(), "用户不存在", Toast.LENGTH_SHORT).show();
                }
            }
        });
        return view;
    }

    private void getEditString(){
        userName=user_name .getText().toString().trim();
        password=psw.getText().toString().trim();
        pswAgain=psw_again.getText().toString().trim();
    }

    /**
     *从SharedPreferences中根据用户名读取密码
     */
    private String readPsw(String userName){
        //getSharedPreferences("loginInfo",MODE_PRIVATE);
        //"loginInfo",mode_private; MODE_PRIVATE表示可以继续写入
        SharedPreferences sp=getContext().getSharedPreferences("loginInfo", MODE_PRIVATE);
        //sp.getString() userName, "";
        return sp.getString(userName , "");
    }

    private boolean isExistUserName(String userName){
        boolean has_userName=false;
        //mode_private SharedPreferences sp = getSharedPreferences( );
        // "loginInfo", MODE_PRIVATE
        SharedPreferences sp=getContext().getSharedPreferences("loginInfo", MODE_PRIVATE);
        //获取密码
        String spPsw=sp.getString(userName, "");//传入用户名获取密码
        //如果密码不为空则确实保存过这个用户名
        if(!TextUtils.isEmpty(spPsw)) {
            has_userName=true;
        }
        return has_userName;
    }

    private void saveRegisterInfo(final String userName, final String psw){
        String md5Psw = MD5Utils.md5(psw);//把密码用MD5加密
        //loginInfo表示文件名, mode_private SharedPreferences sp = getSharedPreferences( );
        SharedPreferences sp=getContext().getSharedPreferences("loginInfo", MODE_PRIVATE);
        //获取编辑器， SharedPreferences.Editor  editor -> sp.edit();
        SharedPreferences.Editor editor=sp.edit();
        //以用户名为key，密码为value保存在SharedPreferences中
        //key,value,如键值对，editor.putString(用户名，密码）;
        editor.putString(userName, md5Psw);
        //提交修改 editor.commit();
        editor.commit();
    }
    private String generateCaptchaCode() {
        // 生成一个随机的 4 位数验证码
        Random random = new Random();
        int code = random.nextInt(9000) + 1000;
        return String.valueOf(code);
    }

    @Override
    public boolean onTouch(View view, MotionEvent motionEvent) {
        return true;
    }
}